import { history, request, useRequest } from '@umijs/max';
import { Button, Spin } from 'antd';
import { useEffect } from 'react';
import Template from '..';

export default () => {
  const { search } = history.location;
  const id = new URLSearchParams(search).get('id') ?? undefined;
  const preview = new URLSearchParams(search).get('preview') ?? undefined;

  const {
    data,
    run: getTemplate,
    loading,
  } = useRequest(
    () => {
      return request(`/api/template/${id}`, {
        method: 'GET',
      });
    },
    {
      manual: true,
    },
  );

  useEffect(() => {
    if (id) {
      getTemplate();
    }
  }, [id, getTemplate]);

  return (
    <>
      <div style={{ marginBottom: 16 }}>
        <Button onClick={() => history.push('/template/list')}>返回</Button>
      </div>
      <Spin spinning={loading}>
        {data?.content && (
          <Template
            initData={data?.content}
            preview={Boolean(Number(preview))}
          />
        )}
      </Spin>
    </>
  );
};
